package system.service.impl;

import common.config.exception.CustomException;
import common.config.jwt.JwtUtil;
import common.config.jwt.TokenInfo;
import common.model.dto.ModifyPasswordToken;
import common.model.enums.EmailValidEnum;
import common.model.enums.UserDeletedEnum;
import common.model.po.SysUser;
import common.model.request.ForgetPasswordRequest;
import common.model.request.SendEmailRequest;
import common.model.response.base.Result;
import common.service.RedissonCacheService;
import common.util.EmailTemplateUtil;
import common.util.UserChecker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import system.service.ForgetPasswordService;
import system.service.MailService;
import system.service.SysUserService;

import javax.annotation.Resource;
import java.util.Collections;

/**
 * 描述
 *
 * @author 米泽鹏
 * @since 2023-11-8 下午 3:13
 */
@Slf4j
@Service
public class ForgetPasswordServiceImpl implements ForgetPasswordService {

	@Resource
	private SysUserService userService;
	@Resource
	private RedissonCacheService redissonCacheService;
	@Resource
	private MailService mailService;
	@Value("${satisfactory.domain}")
	private String domain;

	@Override
	public Result<?> forgetPassword(ForgetPasswordRequest request) {
		String email = request.getEmail();
		SysUser user = userService.lambdaQuery().eq(SysUser::getEmail, email).eq(SysUser::getIsDeleted, UserDeletedEnum.NOT_DELETED.getValue()).oneOpt().orElseThrow(() -> new CustomException("该邮箱未注册"));
		UserChecker.checkUser(user);
		Long userId = user.getId();
		Integer emailValid = user.getEmailValid();
		if (!EmailValidEnum.VALID.getValue().equals(emailValid)) {
			throw new CustomException("邮箱未激活，请联系管理员修改密码。微信搜索公众号：幸福工厂游戏工具，私信即可。");
		}
		// 生成修改密码的token
		ModifyPasswordToken modifyPasswordToken = new ModifyPasswordToken();
		modifyPasswordToken.setUserId(userId);
		TokenInfo tokenInfo = JwtUtil.createModifyPasswordToken(modifyPasswordToken);
		redissonCacheService.cacheModifyPasswordTokenString(userId, tokenInfo.getToken(), tokenInfo.getExpireDate()).throwExceptionIfFailed();
		// 发送邮件
		SendEmailRequest sendEmailRequest = new SendEmailRequest();
		sendEmailRequest.setToList(Collections.singletonList(email));
		sendEmailRequest.setSubject("忘记密码【幸福工厂游戏工具网站】");
		sendEmailRequest.setText(EmailTemplateUtil.getForgetPasswordContent(domain, tokenInfo.getToken(), user.getUsername(), user.getNickname()));
		sendEmailRequest.setHtml(true);
		mailService.sendEmail(sendEmailRequest);
		return Result.success();
	}

}
